﻿using Devil;
using OfficeOpenXml;
using System;
using System.IO;
using TableCore;

namespace TableTranslate
{
    internal class UpdateTextsID : ICommand
    {
        int emptyLines;

        public void Execute()
        {
            var file = Program.ReadText("输入Excel文件: ");
            if (!File.Exists(file))
            {
                Console.WriteLine(string.Format("无效的文件： {0}.", file));
                return;
            }
            Console.WriteLine(string.Format("正在更新文件 {0} 中的翻译文本", file));
            var excel = new ExcelPackage(new FileInfo(file));
            var sheet = excel.Workbook.Worksheets[1];
            int row = 4;
            int txtCol = -1, idCol = -1;
            for (int i = 2; i < 8; i++)
            {
                var str = sheet.Cells[1, i].Text;
                if (StringUtil.EqualIgnoreCase(str, "text") || StringUtil.EqualIgnoreCase(str, "text.cn"))
                {
                    txtCol = i;
                }
                else if(StringUtil.EqualIgnoreCase(str, "id"))
                {
                    idCol = i;
                }
                if (idCol != -1 && txtCol != -1)
                    break;
            }
            if (txtCol == -1 || idCol == -1)
                throw new Exception("没有找到文本列(id, text.cn 或者 text)");
            while (true)
            {
                var txtcell = sheet.Cells[row, txtCol].Text;
                if (string.IsNullOrEmpty(txtcell))
                {
                    emptyLines++;
                    if (emptyLines > 3)
                        break;
                    else
                        continue;
                }
                emptyLines = 0;
                var id = StringUtil.ToHash(txtcell).ToString();
                //var idcell = sheet.Cells[row, 1];
                //idcell.Value = id;
                if (txtCol != idCol)
                {
                    var idcell = sheet.Cells[row, idCol];
                    idcell.Value = id;
                }
                row++;
            }
            excel.Save();
            excel.Dispose();
            Console.WriteLine(file + " Updated.");
        }

        public override string ToString()
        {
            return "更新文本表 ID";
        }
    }
}
